package com.dszq.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dszq.admin.mapper.AdUserMapper;
import com.dszq.admin.service.AdUserService;
import com.dszq.model.admin.dtos.AdUserDto;
import com.dszq.model.admin.pojos.AdUser;
import com.dszq.model.common.dtos.ResponseResult;
import com.dszq.model.common.enums.AppHttpCodeEnum;
import com.dszq.utils.common.AppJwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * [一句话描述该类的功能]
 *
 * @author : [Lenovo]
 * @version : [v1.0]
 * @createTime : [2024/4/29 19:29]
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {
    @Autowired
    private AdUserMapper adUserMapper;
    /**
     * 用户登录接口。
     *
     * @param adUserDto 包含用户登录信息的数据传输对象，通常包括用户名和密码等认证所需信息。
     * @return 返回一个响应结果对象，其中可能包含登录是否成功的信息、令牌（如果登录成功）等。
     */
    @Override
    public ResponseResult login(AdUserDto adUserDto) {
        if(StringUtils.isBlank(adUserDto.getName())||StringUtils.isBlank(adUserDto.getPassword()))
        {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"用户名或密码为空");
        }
        AdUser adUser = adUserMapper.selectOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName,adUserDto.getName()));
        if (adUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        String salt = adUser.getSalt();
        String password = adUserDto.getPassword();
        password = DigestUtils.md5DigestAsHex((password+salt).getBytes());
        if (password.equals(adUser.getPassword())){
            //4.返回数据  jwt
            Map<String,Object> map  = new HashMap<>();
            map.put("token", AppJwtUtil.getToken(adUser.getId().longValue()));
            adUser.setSalt("*****");
            adUser.setPassword("******");
            map.put("user",adUser);
            return ResponseResult.okResult(map);
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
    }
}
